package com.example.esp8266.Library.MQTT;

import android.util.Log;

import androidx.annotation.NonNull;

import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MQTT_Depend {
    public static MqttClient mqttClient;
    String serverURI;
    String server_port;
    String clientId;
    String default_topic;
    String userName;
    String passWord;//默认参数值设置
    MqttCallback mqttCallback;
    public MQTT_Depend(String _serverURI, String _server_port, String _clientId, String _default_topic, String _userName, String _passWord, MqttCallback _mqttCallback)
    {
        serverURI = _serverURI;
        server_port = _server_port;
        clientId = _clientId + "_" + System.currentTimeMillis(); // 设置默认唯一客户端ID

        default_topic = _default_topic;
        if (default_topic == null || default_topic.isEmpty()) {
            default_topic = "TEST"; // 设置默认订阅主题
        }

        userName=_userName;
        passWord=_passWord;
        mqttCallback=_mqttCallback;
        initClient();
    }
    static String TAG = "MQTT_Service";

    // 初始化+连接MQTT函数
    public void initClient() {
        try {
            MemoryPersistence persistence = new MemoryPersistence();
            if (server_port == null || server_port.isEmpty()){
                mqttClient = new MqttClient(serverURI, clientId, persistence);// 创建服务器连接对象
                Log.i(TAG,"准备连接到mqtt服务器");
            }
            else {//如果配置了端口的处理方式
                mqttClient = new MqttClient("tcp://"+serverURI+":"+server_port, clientId, persistence);// 创建服务器连接对象
                Log.i(TAG,"准备连接到mqtt服务器");
            }
            mqttClient.setCallback(mqttCallback);// 设置回调函数


            MqttConnectOptions options = getMqttConnectOptions();//配置连接参数

            //创建服务连接
            mqttClient.connect(options);
            mqttClient.subscribe(default_topic, 0);//默认订阅的主题，质量为0
            publishMessage("SYSTEM","ESP8266_1.OK?",0);
            Log.i(TAG,"Success connect to MQTT server");
        } catch (MqttException me) {
            Log.e(TAG,"initException: " + me.getMessage());
        }
    }

    @NonNull
    private MqttConnectOptions getMqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions(); //创建MQTT连接参数对象
        //设置对应参数
        if (userName != null){//如果配置了登录用户名+密码
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
        }
        options.setAutomaticReconnect(true);// 自动重连
        options.setConnectionTimeout(30);// 设置连接超时时间, 单位为秒,默认30
        options.setKeepAliveInterval(45);// 设置会话心跳时间,单位为秒,默认45
        options.setCleanSession(true);// 清除连接记录
        return options;
    }

    //断开连接函数
    public void disconnect(boolean flag) {
        if(!flag){
            return;
        }
        if(mqttClient.isConnected()) {
            try {
                mqttClient.disconnect();
            } catch (MqttException e) {
                Log.e(TAG, "disconnectException: " + e.getMessage());
            }
        }
    }

    // 订阅主题函数
    // 主题+质量
    public void subscribeTopic(String topic, int qos) {
        if(mqttClient.isConnected()) {
            try {
                mqttClient.subscribe(topic, qos);
                Log.i(TAG, "成功订阅主题：" + topic);
            } catch (MqttException e) {
                Log.e(TAG, "Exception while subscribing to " + topic + ": " + e.getMessage());
            }
        }
    }

    // 发布消息函数
    // 主题+内容+质量
    public void publishMessage(String topic, String payload, int qos) {
        if(mqttClient.isConnected()) {
            try {
                MqttMessage message = new MqttMessage(payload.getBytes());
                message.setQos(qos);
                mqttClient.publish(topic, message);
            } catch (MqttException e) {
                Log.e(TAG, "Exception while publishing message to " + topic + ": " + e.getMessage());
            }
        }
    }
}
